//
//  AvatarController.swift
//  flowerpot
//
//  Created by fyname on 15/11/9.
//  Copyright © 2015年 senhe. All rights reserved.
//

import UIKit
import Toucan

class AvatarController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate{

    @IBOutlet weak var SelectImage: UIImageView!
    
    @IBOutlet weak var ReSelectImage: UIButton!
    
    @IBOutlet weak var OkImage: UIButton!
    
    let imagePickerController:UIImagePickerController = UIImagePickerController()
    
    let currentImage:String = "currentImage.png"
    
    var isFullScreen:Bool = false
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.SelectImage.frame = CGRectMake(100, 100,100, 100)
        self.ReSelectImage.hidden = true
        self.OkImage.hidden = true
        //openMenu()
        initView()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func ReImage(sender: AnyObject) {
        ReSelectImage.hidden = true
        self.OkImage.hidden = true
        initView()
    }
    
    func initView(){
        //设置代理
        self.imagePickerController.delegate = self
        //设置是否可以管理已经存在的图片或者视频
        self.imagePickerController.allowsEditing = true
        
        // 判断是否支持相机
                 if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
                         let alertController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
                         //在iPad上使用表单（ActionSheet）需要设置描点(anchor point)
                         let popover = alertController.popoverPresentationController
                         if (popover != nil){
                                 popover?.sourceView = self.view
                                 popover?.sourceRect = self.view.frame
                                 popover?.permittedArrowDirections = UIPopoverArrowDirection.Any
                             }
            
                         let cameraAction: UIAlertAction = UIAlertAction(title: "拍照换头像", style: .Default) { (action: UIAlertAction!) -> Void in
                                 // 设置类型
                                 self.imagePickerController.sourceType = UIImagePickerControllerSourceType.Camera
                                 self.presentViewController(self.imagePickerController, animated: true, completion: nil)
                             }
                         alertController.addAction(cameraAction)
                         log.debug("使用摄像头拍照 one!")
                         let photoLibraryAction: UIAlertAction = UIAlertAction(title: "从相册选择换头像", style: .Default) { (action: UIAlertAction!) -> Void in
                                 // 设置类型
                                 self.imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                                 //改navigationBar背景色
                                 self.imagePickerController.navigationBar.barTintColor = UIColor(red: 171/255, green: 202/255, blue: 41/255, alpha: 1.0)
                                 //改navigationBar标题色
                                 self.imagePickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
                                 //改navigationBar的button字体色
                                 self.imagePickerController.navigationBar.tintColor = UIColor.whiteColor()
                                 self.imagePickerController.allowsEditing = true
                                 self.presentViewController(self.imagePickerController, animated: true, completion: nil)
                             }
                         alertController.addAction(photoLibraryAction)
            
                    let cancelAction: UIAlertAction = UIAlertAction(title: "取消", style: .Cancel, handler: { (alertAction: UIAlertAction)->() in
                        self.ReSelectImage.hidden = false
                        log.debug("取消选择!")
                    })
                         alertController.addAction(cancelAction)
            
                         presentViewController(alertController, animated: true, completion: nil)
                         log.debug("使用摄像头拍照 two!")
            
                     }else{
                         let alertController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
                         //设置描点(anchor point)
                         let popover = alertController.popoverPresentationController
                         if (popover != nil){
                                 popover?.sourceView = self.view
                                 popover?.sourceRect = self.view.frame
                                 popover?.permittedArrowDirections = UIPopoverArrowDirection.Any
                             }
            
                         let photoLibraryAction: UIAlertAction = UIAlertAction(title: "从相册选择换头像", style: .Default) { (action: UIAlertAction!) -> Void in
                                 // 设置类型
                                 self.imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                                 //改navigationBar背景色
                                 self.imagePickerController.navigationBar.barTintColor = UIColor(red: 171/255, green: 202/255, blue: 41/255, alpha: 1.0)
                                 //改navigationBar标题色
                                 self.imagePickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
                                 //改navigationBar的button字体色
                                 self.imagePickerController.navigationBar.tintColor = UIColor.whiteColor()
                                 self.imagePickerController.allowsEditing = true
                                 self.presentViewController(self.imagePickerController, animated: true, completion: nil)
                                 log.debug("调用相册!")
                             }
                         alertController.addAction(photoLibraryAction)
                    
                         let cancelAction: UIAlertAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
                         alertController.addAction(cancelAction)

                         presentViewController(alertController, animated: true, completion: nil)

                     }
    }

    
    //实现ImagePicker delegate事件
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        picker.dismissViewControllerAnimated(true, completion: nil)
        
        log.debug("图片处理选择!")
        
        //var image:UIImage!
        /*
        //判断，图片是否允许修改
        if(picker.allowsEditing){
            //裁剪后的图片
            image = info[UIImagePickerControllerEditedImage] as! UIImage
        }else{
            //原始图片
            image = info[UIImagePickerControllerOriginalImage] as! UIImage
        }*/
        
        let type :NSString = info["UIImagePickerControllerMediaType"]as! NSString
        if(type.isEqualToString("public.image"))
        {
            let image :UIImage = info["UIImagePickerControllerEditedImage"]as! UIImage
            log.debug("image:\(image)")
            //保存图片到本地
            self.saveImage(Toucan(image: image).maskWithEllipse(borderWidth: 10, borderColor: UIColor.yellowColor()).image, newSize: CGSize(width: 100, height: 100), percent: 0.5, imageName: currentImage)
            //self.saveImage(redrwaImage(image,withParam: 5), newSize: CGSize(width: 100, height: 100), percent: 0.5, imageName: currentImage)
            
            picker.dismissViewControllerAnimated(true, completion:nil)
        
        
            let home = NSHomeDirectory() as NSString;
            let docPath = home.stringByAppendingPathComponent("Documents") as NSString;
            let fullPath = docPath.stringByAppendingPathComponent(currentImage);

            let savedImage: UIImage = UIImage(contentsOfFile: fullPath)!
            self.isFullScreen = false
            self.SelectImage.image = savedImage
            log.debug("保存图片到本地了:\(fullPath)")
           //在这里调用网络通讯方法，上传头像至服务器...
            
            self.ReSelectImage.hidden = false
            self.OkImage.hidden = false
       }
    }
    
    // 当用户取消时，调用该方法
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        self.dismissViewControllerAnimated(true, completion: nil)
        log.debug("取消选择!")
        
    }
    
    
    //设置圆形图片
    func redrwaImage(image:UIImage,withParam inset:CGFloat)->UIImage
    {
        UIGraphicsBeginImageContext(image.size)
        let context:CGContextRef = UIGraphicsGetCurrentContext()!
        CGContextSetLineWidth(context, 2)
        CGContextSetStrokeColorWithColor(context,UIColor.whiteColor().CGColor)
        let rect:CGRect = CGRectMake(inset, inset,CGFloat(image.size.width - inset * 2),CGFloat(image.size.height - inset * 2))
        CGContextAddEllipseInRect(context, rect)
        CGContextClip(context)
        image.drawInRect(rect)
        CGContextAddEllipseInRect(context, rect)
        CGContextStrokePath(context)
        let newing = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newing
        
    }
    
    //保存图片到沙箱
    func saveImage(currentImage: UIImage, newSize: CGSize, percent: CGFloat, imageName: String){
        //压缩图片尺寸
        UIGraphicsBeginImageContext(newSize)
        currentImage.drawInRect(CGRectMake(0, 0,newSize.width,newSize.height))
        let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        //高保真压缩图片质量
        //UIImageJPEGRepresentation此方法可将图片压缩，但是图片质量基本不变，第二个参数即图片质量参数。
        let imageData:NSData = UIImageJPEGRepresentation(newImage, percent)!
        
        // 获取沙盒目录,这里将图片放在沙盒的documents文件夹中
        let home = NSHomeDirectory() as NSString;
        let docPath = home.stringByAppendingPathComponent("Documents") as NSString;
        let fullPath = docPath.stringByAppendingPathComponent(imageName);

        //将图片写入文件
        imageData.writeToFile(fullPath, atomically: false)
    }
    
    //实现点击图片预览功能，滑动放大缩小，带动画
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        log.debug("点击预览图片!")
        
        self.isFullScreen = !self.isFullScreen
        
        let touch: UITouch = touches.first! as UITouch
        let touchPoint: CGPoint = touch.locationInView(self.view)
        let imagePoint: CGPoint = self.SelectImage.frame.origin
         //touchPoint.x ，touchPoint.y 就是触点的坐标
        // 触点在imageView内，点击imageView时 放大,再次点击时缩小
        if(imagePoint.x <= touchPoint.x && imagePoint.x + self.SelectImage.frame.size.width >= touchPoint.x && imagePoint.y <= touchPoint.y
            && imagePoint.y + self.SelectImage.frame.size.height >= touchPoint.y){
               //设置图片放大动画
                UIView.beginAnimations(nil, context: nil)
                //动画事件
                UIView.setAnimationDuration(1)
                if(isFullScreen){
                   //放大尺寸
                    self.SelectImage.frame = CGRectMake(100, 100, 150, 150)
                }else{
                   //缩小尺寸
                   self.SelectImage.frame = CGRectMake(100, 100, 100, 100)
                }
                
                //提交动画
                UIView.commitAnimations()
        }

    }
    
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
